import React, { memo, useRef, useState, useEffect } from "react";
import { useSelector, shallowEqual, useDispatch } from "react-redux";
import { TitleStyle } from "./style";
import { NavLink } from "react-router-dom";
import { mvDetailAction } from "../../../pages/mv/store/actionTypes";
import { videoDetailAction } from "../../../pages/video/store/actionTypes";

export default memo(function VideoTitle(props) {
  const dispatch = useDispatch();

  useEffect(() => {
    if (!props.video) {
      dispatch(mvDetailAction(mvid));
    } else {
      dispatch(videoDetailAction(mvid));
    }
  }, [dispatch, props.mvid, props.video]); // eslint-disable-line react-hooks/exhaustive-deps

  const { mvDetailState } = useSelector(
    (state) => ({
      mvDetailState: !props.video
        ? state.getIn(["mv", "mvDetailR"])
        : state.getIn(["video", "videoDetail"]),
    }),
    shallowEqual
  );

  const mvid = props.mvid;
  return (
    <TitleStyle>
      <div className="mv-name">
        <h2 className="n-mv-title">
          {/[A-Za-z]/.test(mvid) ? "" : <i className="icon2"></i>}
          &nbsp;
          {mvDetailState.length !== 0
            ? props.video
              ? mvDetailState.data.title
              : mvDetailState.data.name
            : ""}
        </h2>
        {props.video ? (
          mvDetailState.length !== 0 ? (
            <div className="fl">
              by&nbsp;
              <NavLink
                to={{
                  pathname: "/artist",
                  search: "?id=" + mvDetailState.data.creator.userId,
                }}
              >
                {mvDetailState.data.creator.nickname}
              </NavLink>
            </div>
          ) : (
            ""
          )
        ) : mvDetailState.length !== 0 ? (
          mvDetailState.data.artists.map((item, index) => {
            return index == 0 ? (
              <NavLink
                to={{
                  pathname: "/artist",
                  search: "?id=" + mvDetailState.data.artistId,
                }}
                key={item.id}
              >
                {item.name}
              </NavLink>
            ) : (
              <React.Fragment key={item.id}>
                &nbsp;/&nbsp;
                <NavLink
                  to={{
                    pathname: "/artist",
                    search: "?id=" + mvDetailState.data.artistId,
                  }}
                >
                  by {item.name}
                </NavLink>
              </React.Fragment>
            );
          })
        ) : (
          ""
        )}
      </div>
    </TitleStyle>
  );
});
